package com.koron.car.web.costregister.service.impl;

import com.alibaba.excel.EasyExcel;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.car.config.Constants;
import com.koron.car.web.applycar.bean.entity.DriverRecord;
import com.koron.car.web.applycar.mapper.DriverRecordMapper;
import com.koron.car.web.common.CommonUtils;
import com.koron.car.web.costregister.bean.entity.CostRegister;
import com.koron.car.web.costregister.bean.query.CostRegisterQuery;
import com.koron.car.web.costregister.bean.vo.CostRegisterExcel;
import com.koron.car.web.costregister.bean.vo.CostRegisterVO;
import com.koron.car.web.costregister.mapper.CostRegisterMapper;
import com.koron.car.web.costregister.service.CostRegisterService;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (CostRegister)表服务实现类
 *
 * @author twcao
 * @since 2022-03-14 12:27:25
 */
@Service
@Slf4j
public class CostRegisterServiceImpl implements CostRegisterService {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("queryById")
    public CostRegisterVO queryById(SessionFactory factory, String id) {
        CostRegisterMapper mapper = factory.getMapper(CostRegisterMapper.class);
        return mapper.queryById(id);
    }

    /**
     * 查询多条数据
     * @param query 查询条件
     * @return 对象列表
     */
    @Override
    @TaskAnnotation("queryList")
    public List<CostRegisterVO> queryList(SessionFactory factory, CostRegisterQuery query) {
        CostRegisterMapper mapper = factory.getMapper(CostRegisterMapper.class);
        return mapper.queryList(query);
    }

    /**
     * 新增数据
     *
     * @param cost 实例对象
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("insert")
    public CostRegisterVO insert(SessionFactory factory, CostRegisterVO cost) {
        CostRegisterMapper mapper = factory.getMapper(CostRegisterMapper.class);
        EamUser eamUser = ThreadLocalContext.get();
        CommonUtils.update(cost, eamUser);
        cost.setDeptId(eamUser.getOrgId());
        cost.setId(CodeTools.getCode32());
        cost.setState(Constants.FeeState.DRAFT);
        mapper.insert(cost);
        return cost;
    }

    /**
     * 修改数据
     * @param cost 实例对象
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("update")
    public CostRegisterVO update(SessionFactory factory, CostRegisterVO cost) {
        CostRegisterMapper mapper = factory.getMapper(CostRegisterMapper.class);
        CommonUtils.update(cost, ThreadLocalContext.get());
        if(cost.getSubmit()) {
            cost.setState(Constants.FeeState.FINISH);
        }
        if (cost.getCostType().equals(Constants.FeeType.PARKFEE)){
            DriverRecord driverRecord = new DriverRecord();
            String driverId = cost.getDriverId();
            String applyId = cost.getApplyId();
            driverRecord.setDriverId(driverId);
            driverRecord.setApplyId(applyId);
            driverRecord.setParkFee(cost.getCost()); // 停车费
            driverRecord.setUpdateTime(cost.getStartTime());
            DriverRecordMapper driverRecordMapper = factory.getMapper(DriverRecordMapper.class);
            driverRecordMapper.updateParkFee(driverRecord);
        }
        mapper.update(cost);
        return queryById(factory, cost.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    @TaskAnnotation("deleteById")
    public boolean deleteById(SessionFactory factory, String id) {
        CostRegisterMapper mapper = factory.getMapper(CostRegisterMapper.class);
        return mapper.deleteById(id) > 0;
    }

    @Override
    @TaskAnnotation("deleteByIds")
    public boolean deleteByIds(SessionFactory factory, List<String> ids) {
        if (CollectionUtils.isEmpty(ids)){
            Assert.notEmpty(ids,"当前删除的元素不存在!");
        }
        CostRegisterMapper mapper = factory.getMapper(CostRegisterMapper.class);
        return mapper.deleteByIds(ids) > 0;
    }

    /**
     * 批量新增ETC 费用
     * @param factory
     * @param costList
     * @return
     */
    @Override
    @TaskAnnotation("saveBatch")
    public List<CostRegister> saveBatch(SessionFactory factory, List<CostRegister> costList) {
        CostRegisterMapper costRegisterMapper = factory.getMapper(CostRegisterMapper.class);
        Assert.notEmpty(costList,"当前新增费用为空，请完整填写费用！");
        // 剔除费用为null或者为0的无效数据
        List<CostRegister> collect = costList.stream().filter(costRegister -> costRegister.getCost() != null && costRegister.getCost() > 0).collect(Collectors.toList());
        collect.forEach(costRegister -> {
            if (costRegister.getId() == null){
                costRegister.setId(CodeTools.getCode32());
            }
            EamUser eamUser = ThreadLocalContext.get();
            CommonUtils.update(costRegister, eamUser);
            costRegister.setCostType(Constants.FeeType.TOILFEE);
            costRegister.setDeptId(eamUser.getOrgId());
            costRegister.setState(Constants.FeeState.DRAFT);
        });
        costRegisterMapper.insertBatch(collect);
        return collect;
    }

    @Override
    @TaskAnnotation("updateBatch")
    public List<CostRegister> updateBatch(SessionFactory factory, List<CostRegister> costList) {
        CostRegisterMapper costRegisterMapper = factory.getMapper(CostRegisterMapper.class);
        Assert.notEmpty(costList,"当前新增费用为空，请完整填写费用！");
        // 剔除费用为null或者为0的无效数据
        List<CostRegister> collect = costList.stream().filter(costRegister -> costRegister.getCost() != null && costRegister.getCost() > 0).collect(Collectors.toList());
        collect.forEach(costRegister -> {
            if (costRegister.getId() == null){
                costRegister.setId(CodeTools.getCode32());
            }
            EamUser eamUser = ThreadLocalContext.get();
            CommonUtils.update(costRegister, eamUser);
            costRegister.setCostType(Constants.FeeType.TOILFEE);
            costRegister.setDeptId(eamUser.getOrgId());
            costRegister.setState(Constants.FeeState.FINISH);
        });
        costRegisterMapper.updateBatch(collect);
        return collect;
    }

    @Override
    @TaskAnnotation("importOilCostExcel")
    public void importOilCostExcel(SessionFactory factory,MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        EasyExcel.read(in, CostRegisterExcel.class, new StorageListener(factory)).sheet().doRead();
    }

    @Override
    @TaskAnnotation("importRepairFeeCostExcel")
    public void importRepairFeeCostExcel(SessionFactory factory, MultipartFile file) {
        InputStream in = null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        new RepairFeeStorageListener(factory).read(in,3);
    }

    @Override
    @TaskAnnotation("queryByIds")
    public List<CostRegisterVO> queryByIds(SessionFactory factory, List<String> ids) {
        Assert.notEmpty(ids,"参数不合法！");
        CostRegisterMapper costRegisterMapper = factory.getMapper(CostRegisterMapper.class);
        return costRegisterMapper.queryByIds(ids);
    }
}
